package com.bing.beike.service;

import cn.dev33.satoken.stp.StpUtil;
import com.bing.beike.entity.RoleEnum;
import com.bing.beike.entity.User;
import com.bing.beike.mapper.UserMapper;
import com.bing.beike.util.EncryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    public UserMapper userMapper;

    public int register(User user) {
        if (userMapper.findByUsername(user.getUsername()) != null) {
            return -1;
        }
        if (userMapper.findByEmail(user.getEmail())) {
            return -2;
        }
        user.setRealName("xxx");
        user.setRole(RoleEnum.teacher);

        user.setPasswordHash(EncryptUtils.encryptToMD5(user.getPasswordHash()));
        return userMapper.register(user);
    }


    public User findByUsername(String username) {
        try {
            return userMapper.findByUsername(username);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public User login(User user) {
        if (user.getUsername() == null || user.getPasswordHash() == null) {
            return null;
        }
        user.setPasswordHash(EncryptUtils.encryptToMD5(user.getPasswordHash()));
        try {
            return userMapper.login(user);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

//    public void logout(String username) {
//        try {
//            StpUtil.logout(username);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
}
